﻿using AutoMapper;
using CBLibrary.JwtBearer.Model;
using CBLibrary.Repository.Application;
using CBLibrary.Repository.Cache;
using CBLibrary.Repository.Extensions;
using CBLibrary.Repository.Repository;
using CBLibrary.Repository.UnitOfWork;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using RepositoryTestWeb.Entity;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace RepositoryTestWeb.AppService
{
    /// <summary>
    /// 添加审计+修改审计+删除审计+软删除
    /// </summary>
    public class UserService : AppServiceFullAudited<UserService, Guid, UserEntity, UserDto>, IUserService
    {
        /// <summary>
        /// 缓存key,为空不启用缓存
        /// </summary>
        protected override string Cachekey { get; set; } = "User:All";

        public UserService(
            ILogger<UserService> logger,
            IMapper mapper,
            IHttpContextAccessor accessor,
            IUnitOfWork unitOfWork,
            ICacheService cacheService,
            IRepositoryWithGuid<UserEntity> repository) : base(logger, mapper, accessor, unitOfWork, cacheService, repository)
        {

        }

        public async Task<ResultMessage<UserDto>> GetByUserNameAsync(string userName)
        {
            base.Logger.LogInformation("GetByUserNameAsync 输入参数:{0}", userName);

            var user = await Repository.QueryAsync(u => u.UserName.Equals(userName.Trim(), StringComparison.OrdinalIgnoreCase));

            var userDto = base.Mapper.Map<UserDto>(user);

            if (null != userDto)
            {
                return new ResultMessage<UserDto>(userDto, 1, AppConstants.M_GET_SUCCESS);
            }

            return new ResultMessage<UserDto>(null, AppConstants.C_FAILURE, AppConstants.M_GET_FAILURE);
        }

        public async Task<ResultMessage<UserDto>> LoginAsync(AuthenticateInput input)
        {
            var dto = (await GetByPredicateAsync(p => p.UserName.EqualsWithIgnoreCase(input.UserName.Trim()))).SingleOrDefault();

            if (null == dto)
            {
                return new ResultMessage<UserDto>(null, AppConstants.C_NOTFOUND, AppConstants.M_NOTEXIST);
            }

            if (false == dto.Password.Equals(input.Password.Trim()))
            {
                return new ResultMessage<UserDto>(null, AppConstants.C_BADREQUEST, AppConstants.M_BADREQUEST);
            }

            return new ResultMessage<UserDto>(dto);
        }

    }
}
